const DB = require('../../config/DB')
const {
    Op
} = require('sequelize')
DB.note.belongsTo(DB.user)
DB.comment.belongsTo(DB.user)
DB.reply.belongsTo(DB.comment)
DB.note.hasMany(DB.comment)
class NoteController {
    // 获取话题排行榜
    async getTopicTop(ctx) {
        const data = await DB.topic.findAll({
            limit: 10,
            order: [
                ['browse', 'DESC'],
                ['count', 'DESC']
            ]
        })
        global.Response.success(ctx, undefined, data)
    }
    // 搜索排行榜
    async getSearchTop(ctx) {
        const data = await DB.search.findAll({
            limit: 10,
            order: [
                ['count', 'DESC']
            ]
        })
        global.Response.success(ctx, undefined, data)
    }

    async test(ctx)
    {
        global.Response.success(ctx, undefined, [])
    }
    
    //获得类型列表
    async getLeiXing(ctx)
    {

        const data = await DB.leixing.findAll({
            limit: 100
           
        })
        global.Response.success(ctx, undefined, data)
    }

    //获取笔记列表
    async listNote(ctx) {
        // 参数
        let {
            page = 1, size = 10,leixing=0,
        } = ctx.query

        page = Number(page)
        size = Number(size)
        if(leixing=='0')
        {
            const {
                count,
                rows
            } = await DB.note.findAndCountAll({
                offset: (page - 1) * size,
                limit: size,
                order: [
                    ['createdAt', 'DESC']
                ],
                where: {
                    status: 1, // 显示状态为可见
                    check: 1
                },
                include: [{
                    model: DB.user,
                    attributes: ['id', 'name', 'avatar']
                }]
            })
            const data = {
                rows,
                meta: {
                    size, // 每页条目
                    count: count, // 条目总数
                    page: page, // 当前页数
                    total: Math.ceil(count / size), // 总页数
                }
            }
            global.Response.success(ctx, undefined, data)
        }
        else
        {
            const {
                count,
                rows
            } = await DB.note.findAndCountAll({
                offset: (page - 1) * size,
                limit: size,
                order: [
                    ['createdAt', 'DESC']
                ],
                where: {
                    status: 1, // 显示状态为可见
                    check: 1,
                    leixing: leixing
                },
                include: [{
                    model: DB.user,
                    attributes: ['id', 'name', 'avatar']
                }]
            })
            const data = {
                rows,
                meta: {
                    size, // 每页条目
                    count: count, // 条目总数
                    page: page, // 当前页数
                    total: Math.ceil(count / size), // 总页数
                }
            }
            global.Response.success(ctx, undefined, data)
        }
        
    }
    // 笔记详情
    async getDetail(ctx) {
        // userId可选项，判断已点赞、收藏
        let { id: noteId, userId = '' } = ctx.query
        const note = await DB.note.findOne({
            where: {
                id: noteId
            },
            include: [{
                model: DB.user,
                attributes: ['id', 'name', 'avatar']
            }, {
                model: DB.comment,
                include: [
                    {
                        model: DB.user,
                        attributes: ['id', 'avatar', 'name']
                    }
                ]
            }
            ]
        })
        // 加载回复
        let msg = 0 // 消息数量
        for (let commentItem of note.comments) {
            msg++
            const replies = await DB.reply.findAll({
                where: {
                    commentId: commentItem.get('id'),
                    status: 1 // 审核通过
                }
            })
            for (let row of replies) {
                msg++
                let userId = row.get('userId')
                let replyUserId = row.get('replyUserId')
                // 回复用户
                let user = await DB.user.findByPk(userId, {
                    attributes: ['id', 'avatar', 'name']
                })
                // 被回复用户
                let replyUser = await DB.user.findByPk(replyUserId, {
                    attributes: ['id', 'avatar', 'name']
                })
                row.dataValues.user = user
                row.dataValues.replyUser = replyUser
            }
            commentItem.dataValues.replies = replies
        }
        note.dataValues.msg = msg
        const isLike = await DB.like.findOne({
            where: {
                noteId,
                userId
            }
        })
        const isFavorite = await DB.favorite.findOne({
            where: {
                noteId,
                userId
            }
        })
        note.dataValues.isLike = isLike ? true : false
        note.dataValues.isFavorite = isFavorite ? true : false
        if (note.userId != userId) { // 不能自己关注自己
            const isFocus = await DB.fans.findOne({
                where: {
                    userId: note.userId,
                    fansId: userId
                }
            })
            note.dataValues.isFocus = isFocus ? true : false
        }
        // 增加话题浏览量
        for (let row of note.topic) {
            const [item, created] = await DB.topic.findOrCreate({
                where: { name: row.trim() },
                defaults: {
                    browse: 1,
                    createdAt: global.Moment().format('YYYY-MM-DD HH:mm:ss'),
                    updatedAt: global.Moment().format('YYYY-MM-DD HH:mm:ss')
                }
            })
            if (!created) {
                item.browse++
                item.updatedAt = global.Moment().format('YYYY-MM-DD HH:mm:ss')
                await item.save()
            }
        }
        // 增加笔记浏览量
        note.browse++
        await note.save()
        global.Response.success(ctx, undefined, note)
    }
    async deleteNote(ctx) {
        const { noteId, userId } = ctx.request.body // 必须本人才能删除
        const note = await DB.note.destroy({
            where: {
                id: noteId,
                userId
            }
        }) // 返回值 0 or 1
        if (!note) {
            global.Response.null(ctx)
        }
        // 删除其下评论和回复
        let comments = await DB.comment.findAll({
            where: {
                noteId
            }
        })
        if (comments.length > 0) {
            for (let i in comments) {
                await DB.reply.destroy({
                    where: {
                        commentId: comments[i].get('id')
                    }
                })
            }
        }
        // 删除收藏及点赞
        await DB.favorite.destroy({
            where: {
                noteId
            }
        })
        await DB.like.destroy({
            where: {
                noteId
            }
        })
        await DB.comment.destroy({
            where: {
                noteId
            }
        })
        global.Response.success(ctx, '删除成功')
    }
    async addLike(ctx) {
        let {
            noteId,
            userId,
            cancel = false
        } = ctx.request.body
        let msg = ''
        // 防止重复点赞或者取消点赞
        const exist = await DB.like.findOne({
            where: {
                userId,
                noteId
            }
        })
        // 取消点赞
        if (cancel && exist) {
            await DB.note.decrement({
                like: 1
            }, {
                where: {
                    id: noteId
                }
            })
            await DB.like.destroy({
                where: {
                    userId,
                    noteId
                }
            })
            msg = '点赞取消成功'
        } else if (!exist && !cancel) {
            await DB.note.increment({
                like: 1
            }, {
                where: {
                    id: noteId
                }
            })
            await DB.like.create({
                noteId,
                userId,
                createdAt: global.Moment().format('YYYY-MM-DD HH:mm:ss'),
                updatedAt: global.Moment().format('YYYY-MM-DD HH:mm:ss'),
            })
            msg = '点赞成功'
        } else {
            msg = '数据异常'
        }
        global.Response.success(ctx, msg, undefined)
    }
    async addFavorite(ctx) {
        let {
            noteId,
            userId,
            cancel = false
        } = ctx.request.body
        let msg = ''
        // 防止重复
        const exist = await DB.favorite.findOne({
            where: {
                userId,
                noteId
            }
        })
        if (cancel && exist) {
            await DB.note.decrement({
                favorite: 1
            }, {
                where: {
                    id: noteId
                }
            })
            await DB.favorite.destroy({
                where: {
                    userId,
                    noteId
                }
            })
            msg = '收藏取消成功'
        } else if (!exist && !cancel) {
            await DB.note.increment({
                favorite: 1
            }, {
                where: {
                    id: noteId
                }
            })
            await DB.favorite.create({
                noteId,
                userId,
                createdAt: global.Moment().format('YYYY-MM-DD HH:mm:ss'),
                updatedAt: global.Moment().format('YYYY-MM-DD HH:mm:ss'),
            })
            msg = '收藏成功'
        } else {
            msg = '数据异常'
        }
        global.Response.success(ctx, msg, undefined)
    }
    async addBrowse(ctx) {
        let {
            noteId,
            userId
        } = ctx.request.body

        await DB.note.increment({
            browse: 1
        }, {
            where: {
                id: noteId
            }
        })
        await DB.browse.create({
            noteId,
            userId,
            createdAt: global.Moment().format('YYYY-MM-DD HH:mm:ss'),
            updatedAt: global.Moment().format('YYYY-MM-DD HH:mm:ss'),
        })
        global.Response.success(ctx, undefined, undefined)
    }
    async createNote(ctx) {
        // 参数
        let {
            title, // 标题
            content, // 内容
            carousel = '[]',
            topic = '[]',
            userId,
            status = 1,
            leixing,
        } = ctx.request.body
        carousel = JSON.parse(carousel)
        topic = JSON.parse(topic)
        //leixing="hello";
        // 创建文章
        const note = await DB.note.create({
            leixing,
            title,
            content,
            carousel,
            topic,
            userId,
            status,
            createdAt: global.Moment().format('YYYY-MM-DD HH:mm:ss'),
            updatedAt: global.Moment().format('YYYY-MM-DD HH:mm:ss'),
        }, {
            include: DB.article_info
        })
        for (let row of topic) {
            const [item, created] = await DB.topic.findOrCreate({
                where: { name: row.trim() },
                defaults: {
                    createdAt: global.Moment().format('YYYY-MM-DD HH:mm:ss'),
                    updatedAt: global.Moment().format('YYYY-MM-DD HH:mm:ss')
                }
            })
            if (!created) {
                item.count++
                item.updatedAt = global.Moment().format('YYYY-MM-DD HH:mm:ss')
                await item.save()
            }
        }
        global.Response.success(ctx, '创建成功', note)
    }
    // 搜索
    async searchNote(ctx) {
        // 参数
        let {
            key,
            page = 1, size = 10
        } = ctx.request.query
        key = key.trim()
        if (!key) {
            global.Response.success(ctx, undefined, {
                rows: [],
            })
            return false
        }
        page = Number(page)
        size = Number(size)
        const {
            count,
            rows
        } = await DB.note.findAndCountAll({
            offset: (page - 1) * size,
            limit: size,
            order: [
                ['id', 'DESC']
            ],
            where: {
                title: {
                    [Op.like]: `%${key}%`
                },
                status: 1, // 显示状态为可见
                check: 1
            },
            include: [{
                model: DB.user,
                attributes: ['id', 'name', 'avatar']
            }]
        })
        // 更新搜索关键词
        const [searchKey, created] = await DB.search.findOrCreate({
            where: { key },
            defaults: {
                count: 1,
                createdAt: global.Moment().format('YYYY-MM-DD HH:mm:ss'),
                updatedAt: global.Moment().format('YYYY-MM-DD HH:mm:ss')
            }
        })
        if (!created) {
            searchKey.count++
            searchKey.updatedAt = global.Moment().format('YYYY-MM-DD HH:mm:ss')
            await searchKey.save()
        }
        const data = {
            rows,
            meta: {
                key,
                size, // 每页条目
                count: count, // 条目总数
                page: page, // 当前页数
                total: Math.ceil(count / size), // 总页数
            }
        }
        global.Response.success(ctx, undefined, data)
    }
}

module.exports = new NoteController
